package main

import (
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"sync"
	"time"
)

type Order struct {
	orderID int
	price   float64
}

type PricingStrategy interface {
	getDiscountedPrice(orderID int) float64
	getName() string
}

type Supplier struct {
	name string
}

func (s *Supplier) getDiscountedPrice(orderID int) float64 {

	// 创建 HTTP 客户端
	client := &http.Client{
		Timeout: 10 * time.Second, // 设置超时时间为5秒

	}

	// 创建请求对象
	req, err := http.NewRequest("GET", "http://localhost:3000", nil) // 替换为你要请求的URL
	if err != nil {
		fmt.Println("Error creating request:", err)
		return 0
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return 0
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return 0
	}

	// 处理响应
	fmt.Println(string(body))
	// 模拟获取折扣价格的操作
	return rand.Float64() * 100
}

func (s *Supplier) getName() string {
	return s.name
}

type OrderProcessor struct {
	order     Order
	suppliers []PricingStrategy
	wg        *sync.WaitGroup
}

func (op *OrderProcessor) processOrder() {
	defer op.wg.Done()

	for _, supplier := range op.suppliers {
		discountedPrice := supplier.getDiscountedPrice(op.order.orderID)
		profit := discountedPrice - op.order.price

		fmt.Printf("%s ==> 订单 %d 价格：%f, 供应商价格：%f, 优惠差价：%f\n",
			supplier.getName(), op.order.orderID, op.order.price, discountedPrice, profit)
	}
}

func main() {
	// 记录开始时间
	startTime := time.Now()

	var wg sync.WaitGroup
	var suppliers []PricingStrategy
	suppliers = append(suppliers, &Supplier{name: "Supplier1"})
	suppliers = append(suppliers, &Supplier{name: "Supplier2"})

	for i := 1; i <= 10; i++ {
		wg.Add(1)
		order := Order{orderID: i, price: rand.Float64() * 1000}
		go func(order Order) {
			orderProcessor := OrderProcessor{order: order, suppliers: suppliers, wg: &wg}
			orderProcessor.processOrder()
		}(order)
	}

	// 等待所有goroutine完成
	wg.Wait()

	// 记录结束时间
	elapsedTime := time.Since(startTime)

	// 打印程序耗时
	fmt.Printf("Elapsed Time: %s\n", elapsedTime)
}
